package org.webcamp.results.dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.webcamp.results.dao.ResultsDao;
import org.webcamp.results.dto.QuestionaryResult;

public class ResultsDaoImpl extends JdbcTemplate implements ResultsDao {

	@Override
	public void addResult(QuestionaryResult res) {
		Connection conn = null;
		try {
			conn = getDataSource().getConnection();
			PreparedStatement ps = conn.prepareStatement("insert into results (date, questionary_name, user_id, result) values (?,?,?,?)");
			ps.setDate(1, new Date(res.getDate().getTime()));
			ps.setString(2, res.getQuestionaryName());
			ps.setInt(3, res.getUserId());
			ps.setString(4, res.getResult());
			ps.executeUpdate();
			System.out.println("Result was saved");
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public List<QuestionaryResult> getUserResult(int userId) {
		List<QuestionaryResult> res = new ArrayList<>();
		Connection conn = null;
		try {
			conn = getDataSource().getConnection();

			PreparedStatement ps = conn.prepareStatement("select id, date, questionary_name, user_id, result from results where user_id=?");
			ps.setInt(1, userId);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				QuestionaryResult qr = new QuestionaryResult();
				qr.setDate(rs.getDate("date"));
				qr.setQuestionaryName(rs.getString("questionary_name"));
				qr.setResult(rs.getString("result"));
				qr.setId(rs.getInt("id"));
				qr.setUserId(rs.getInt("user_id"));
				res.add(qr);
			}
			System.out.println("All users were loaded");
			return res;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
